from __future__ import with_statement
import pygame
import sys,math
import mod_actor,mod_game,mod_line,mod_direction,mod_item
import mod_command
import mod_widgets
import mod_vector
import mod_player
import mod_verbs

class GamePanel(mod_widgets.Widget):
    def __init__(self,game,gui):
        self.gui = gui
        self.tileWidth = 32
        size = (1,1)
        self.rect = pygame.Rect((0,0),size)
        self.surface = pygame.surface.Surface(size)
        self.game = game
        self.highlightedSpace = None
        self.potentialTargetPath = None
        self.drawAll = True
        self.dirtyTiles = set()
        
    def handleClick(self,coords,button):
        if button == 1 and self.highlightedSpace:
            actor = self.gui.currentPlayer
            level,coords = actor.location
            brain = actor.brain
            levelMemory = self.gui.currentLevelMemory
            if self.gui.mode == 'go':
                if brain.canReach(self.highlightedSpace) and self.highlightedSpace != coords:
                    self.gui.command = mod_command.Command(mod_verbs.staticTravelVerb,actor,target=self.highlightedSpace)
            elif self.gui.mode == 'target':
                if self.gui.command.targetType == 'coords':
                    if self.highlightedSpace in levelMemory.visibleTiles and self.highlightedSpace != coords:
                        self.gui.command.target = self.highlightedSpace
                elif self.gui.command.targetType == 'dir':
                    if self.highlightedSpace in actor.neighbors:
                        xOffset = self.highlightedSpace[0] - coords[0]
                        yOffset = self.highlightedSpace[1] - coords[1]
                        dir = mod_direction.getDirFromOffset((xOffset,yOffset))
                        self.gui.command.target = dir
                        
    def handleMouseOver(self,mouseCoords):
        player = self.gui.currentPlayer
        level,coords = player.location
        brain = player.brain
        (x,y) = self.getCoordsInLevel(mouseCoords)
        if (x,y) in level.spaceMap:
            self.highlightedSpace = (x,y)
        else:
            self.highlightedSpace = None
        if self.gui.mode == 'go' and brain.canReach(self.highlightedSpace) and self.highlightedSpace != coords:
            self.gui.possibleCommand = mod_command.Command(mod_verbs.staticTravelVerb,player,target=self.highlightedSpace)
                    
    def update(self):
        actor = self.gui.currentPlayer
        level,coords = actor.location
        brain = self.gui.currentPlayer.brain
        levelMemory = self.gui.currentLevelMemory
        
        mode = self.gui.mode
        if mode == 'go':
            if self.highlightedSpace and brain.canReach(self.highlightedSpace) and self.highlightedSpace != coords:
                self.potentialTargetPath = brain.findShortestPath(self.highlightedSpace)
            else:
                self.potentialTargetPath = []
            self.draw(distanceMap=True)
        elif mode == 'target':
            self.draw()
            if self.gui.command.targetType == 'coords':
                if self.highlightedSpace in levelMemory.visibleTiles and self.highlightedSpace != coords:
                    line = mod_line.getBulletLine(actor.location[0],actor.location[1],self.highlightedSpace)
                    self.drawLineOfFire(line)
                    self.drawCrosshairs()
            elif self.gui.command.targetType == 'dir':
                self.lightenNeighbors()
                if self.highlightedSpace in actor.neighbors:
                    self.drawCrosshairs()
        elif isinstance(mode,Animation):
            mode.drawFrame()
        return self.surface
    
    def getRect(self):
        return self.rect
    
    def draw(self,distanceMap=False,dontShow=None):
        levelMemory = self.gui.currentLevelMemory
        #print levelMemory.levelNum
        player = self.gui.currentPlayer
        brain = player.brain
        level,coords = player.location
        
        #print levelMemory.visibleTiles
        
        if distanceMap:
            reachableTiles = brain.getReachableTiles()
        
        if self.drawAll:
            tilesToDraw = levelMemory.spaceMap.keys()
        else:
            tilesToDraw = levelMemory.visibleTiles | levelMemory.extraUpdatedTiles | self.dirtyTiles
        
        for tile in tilesToDraw:
            drawCoords = self.getCoordsInPanel(tile)
            # Draw tile:
            tileGlyph = levelMemory.spaceMap.get(tile)
            if tileGlyph:
                self.surface.blit(self.gui.graphicsMap[tileGlyph],drawCoords)
                
                # Draw distance map info:
                if distanceMap:
                    if tile in reachableTiles and tile != coords:
                        self.surface.blit(self.gui.graphicsMap['MISC_PASSABLE'],drawCoords)
                    if tile in self.potentialTargetPath:
                        self.surface.blit(self.gui.graphicsMap['MISC_ONPATH'],drawCoords)
                
                # Draw item:
                items = levelMemory.itemMap.get(tile)
                if items:
                    topItem = items[-1]
                    self.surface.blit(self.gui.graphicsMap[topItem.glyph],drawCoords)
                # Draw entity:
                entity = levelMemory.entityMap.get(tile)
                if entity and not (dontShow and entity.ID == dontShow.ID):
                    self.surface.blit(self.gui.graphicsMap[entity.glyph],drawCoords)
            else:
                self.surface.blit(self.gui.graphicsMap['MISC_DARK'],drawCoords)
        
        if self.drawAll:
            tilesToFog = set(levelMemory.spaceMap.keys()) - levelMemory.visibleTiles
        else:
            changedTiles = levelMemory.extraUpdatedTiles | (self.dirtyTiles & set(levelMemory.spaceMap.keys())) 
            tilesToFog = (changedTiles - levelMemory.visibleTiles) | levelMemory.newlyNonVisibleTiles
        
        # Gray out tiles that have just left the view:
        for tile in tilesToFog:
            drawCoords = self.getCoordsInPanel(tile)
            self.surface.blit(self.gui.graphicsMap['MISC_FOG'],drawCoords)
        levelMemory.newlyNonVisibleTiles.clear()
        levelMemory.extraUpdatedTiles.clear()
        self.dirtyTiles.clear()
        
        if self.drawAll:
            scrollPoint = self.getCoordsInPanel(player.location[1])
            self.gui.scrollIfNecessary(scrollPoint)
            self.drawAll = False
        

    def drawLineOfFire(self,points):
        for coords in points[:-1]:
            x,y = self.getCoordsInPanel(coords)
            self.surface.blit(self.gui.graphicsMap['MISC_TARGETLINE'],(x,y))

    def drawCrosshairs(self):
        level = self.gui.currentPlayer.location[0]
        if self.highlightedSpace != None and self.highlightedSpace in level.spaceMap:
            x,y = self.getCoordsInPanel(self.highlightedSpace)
            targetGraphic = self.gui.command.targetingGlyph
            if targetGraphic:
                self.surface.blit(self.gui.graphicsMap[targetGraphic],(x,y))
            else:
                self.surface.blit(self.gui.graphicsMap['MISC_CROSSHAIRS'],(x,y))
    
    def lightenNeighbors(self):
        player = self.gui.currentPlayer
        level = player.location[0]
        for neighbor in player.neighbors:
            if neighbor in level.spaceMap:
                x,y = self.getCoordsInPanel(neighbor)
                self.surface.blit(self.gui.graphicsMap['MISC_LIGHT'],(x,y))
    
    def getCoordsInLevel(self,mousePos):
        x = (mousePos[0] / self.tileWidth)
        y = (mousePos[1] / self.tileWidth)
        return (x,y)
    
    def getCoordsInPanel(self,spaceCoords):
        x = spaceCoords[0] * self.tileWidth
        y = spaceCoords[1] * self.tileWidth
        return (x,y)
    
    def displayNewLevel(self,level):
        size = mod_vector.multiplyVector(level.size,self.tileWidth)
        self.rect = pygame.Rect((0,0),size)
        self.surface = pygame.surface.Surface(size)
        self.drawAll = True
    

class Animation:
    pass

class MoveAnimation(Animation):
    def __init__(self,moveEvent,gui):
        player = gui.currentPlayer
        brain = player.brain
        self.gui = gui
        self.moveEvent = moveEvent
        level = player.location[0]
        
        if brain.canSeeLocation(moveEvent.oldLocation) or brain.canSeeLocation(moveEvent.newLocation):
            self.dirtyTiles = set()
            oldCoords = moveEvent.oldLocation[1]
            newCoords = moveEvent.newLocation[1]
            
            self.dirtyTiles.add(oldCoords)
            self.dirtyTiles.add(newCoords)
            self.dirtyTiles.add((oldCoords[0],newCoords[1]))
            self.dirtyTiles.add((newCoords[0],oldCoords[1]))
            
            self.startX,self.startY = gui.gamePanel.getCoordsInPanel(oldCoords)
            self.xOffset = newCoords[0] - oldCoords[0]
            self.yOffset = newCoords[1] - oldCoords[1]
            self.frame = 0
            self.finished = False
        else:
            self.finished = True
        
    def drawFrame(self):
        if not self.finished:
            gamePanel = self.gui.gamePanel
            moveEvent = self.moveEvent
            gamePanel.draw(dontShow=self.moveEvent.actor)
            gamePanel.dirtyTiles.update(self.dirtyTiles)
            x = self.startX + (self.xOffset * self.frame)
            y = self.startY + (self.yOffset * self.frame)
            gamePanel.surface.blit(self.gui.graphicsMap[self.moveEvent.actor.glyph],(x,y))
            self.frame += 8
            if self.frame >= 32:
                self.finished = True
                
    def getCenterPoint(self):
        if not self.finished:
            return (self.startX,self.startY)
        else:
            return None

class ProjectileAnimation(Animation):
    def __init__(self,projectileEvent,gui):
        self.gui = gui
        targetCoords = projectileEvent.line[-1]
        xVector = targetCoords[0] - projectileEvent.originCoords[0]
        yVector = targetCoords[1] - projectileEvent.originCoords[1]
        length = math.sqrt(xVector**2 + yVector**2)
        
        pixelLength = int(length * 32)
        
        self.image = gui.graphicsMap[projectileEvent.projectileGlyph]
        
        if projectileEvent.rotateImage:
            angle = math.degrees(math.atan2(yVector,xVector))
            self.image = pygame.transform.rotate(self.image,-angle)
        
        self.dx = float(xVector*32) / pixelLength
        self.dy = float(yVector*32) / pixelLength
        
        self.startX,self.startY = gui.gamePanel.getCoordsInPanel(projectileEvent.originCoords)
        
        playRatio = float(len(projectileEvent.path))/len(projectileEvent.line)
        self.framesToShow = int((pixelLength * playRatio) - 12)
        
        self.frame = 24
        
        self.finished = False
    
    def drawFrame(self):
        gamePanel = self.gui.gamePanel
        gamePanel.draw()
        x = self.startX + int(math.floor(self.dx * self.frame))
        y = self.startY + int(math.floor(self.dy * self.frame))
        gamePanel.surface.blit(self.image,(x,y))
        
        imageRect = self.image.get_rect().move((x,y))
        gamePanel.dirtyTiles.add(gamePanel.getCoordsInLevel(imageRect.topleft))
        gamePanel.dirtyTiles.add(gamePanel.getCoordsInLevel(imageRect.topright))
        gamePanel.dirtyTiles.add(gamePanel.getCoordsInLevel(imageRect.bottomleft))
        gamePanel.dirtyTiles.add(gamePanel.getCoordsInLevel(imageRect.bottomright))
        
        self.frame += 20
        if self.frame >= self.framesToShow:
            self.finished = True
            
    def getCenterPoint(self):
        return (self.startX,self.startY)


class AOEAnimation(Animation):
    def __init__(self,aofEvent,gui):
        self.gui = gui
        self.finished = False
        self.frame = 0
        self.explosionGraphic = gui.graphicsMap[aofEvent.explosionGlyph]
        self.aofEvent = aofEvent
        
        self.dirtyTiles = set()
        for tile,distance in self.aofEvent.affectedTiles:
            self.dirtyTiles.add(tile)
    
    def drawFrame(self):
        gamePanel = self.gui.gamePanel
        gamePanel.draw()
        gamePanel.dirtyTiles.update(self.dirtyTiles)
        
        for tile,distance in self.aofEvent.affectedTiles:
            drawCoords = gamePanel.getCoordsInPanel(tile)
            gamePanel.surface.blit(self.explosionGraphic,drawCoords)
        
        self.frame += 1
        if self.frame >= 20:
            self.finished = True
            
    def getCenterPoint(self):
        return self.gui.gamePanel.getCoordsInPanel(self.aofEvent.origin)


class StatusBar(mod_widgets.Widget):
    def __init__(self,size,gui):
        self.statusBarFont = pygame.font.Font(None,32)
        self.surface = pygame.surface.Surface(size)
        self.rect = self.surface.get_rect()
        self.gui = gui
        
    def update(self):
        self.surface.fill((192,192,192))
        player = self.gui.currentPlayer
        statusLine = 'HP: '+str(player.HP)+'/'+str(player.maxHP)+'   AP: '+str(player.AP)
        command = self.gui.possibleCommand
        if not command:
            command = self.gui.command
        if command:
            statusLine += '       '+command.name
            APcost = command.calculateAP()
            if APcost != 0:
                statusLine += ' ('+str(APcost)+' AP)'
            #statusLine += ', '+str(self.gui.currentPlayer.AP-verb.AP)+')'
        text = self.statusBarFont.render(statusLine, 1, (0, 0, 0))
        self.surface.blit(text,(6,6))
        return self.surface
        
    def getRect(self):
        return self.rect


class MessageBox(mod_widgets.Widget):
    def __init__(self,size,gui):
        self.gui = gui
        self.surface = pygame.surface.Surface(size)
        self.rect = self.surface.get_rect()
    
    def update(self):
        self.surface.fill((255,255,255))
        pygame.draw.rect(self.surface,(0,0,0),self.rect,1)
        yPosition = 2
        maxMessages = self.rect.height / 16
        for message in self.gui.messages[(-maxMessages):]:
            text = self.gui.distanceMapFont.render(message, 1, (0, 0, 0))
            self.surface.blit(text,(2,yPosition))
            yPosition += 16
        return self.surface
        
    def getRect(self):
        return self.rect


class EndTurnCommand:
    def __init__(self):
        self.targetType = None
        self.iconGlyph = 'BUTTON_ENDTURN'
        self.name = 'END TURN'
    
    def calculateAP(self):
        return 0

staticEndTurnCommand = EndTurnCommand()
#staticEndTurnComamnd


class CommandButton(mod_widgets.Image):
    def __init__(self,command,gui):
        image = gui.graphicsMap[command.iconGlyph]
        mod_widgets.Image.__init__(self,image)
        self.command = command
        self.gui = gui
        self.disabledSurface = None
        
    def handleClick(self,coords,button):
        player = self.gui.currentPlayer
        if player.AP >= self.command.calculateAP() and button == 1:
            self.gui.command = self.command
            
    def handleMouseOver(self,coords):
        self.gui.possibleCommand = self.command
            
    def update(self):
        player = self.gui.currentPlayer
        if player.AP >= self.command.calculateAP():
            return self.surface
        else:
            if self.disabledSurface == None:
                whiteSurface = pygame.surface.Surface(self.surface.get_size())
                whiteSurface.fill((128,128,128))
                whiteSurface.set_alpha(192)
                self.disabledSurface = self.surface.copy()
                self.disabledSurface.blit(whiteSurface,(0,0))
            return self.disabledSurface


class AbilitiesPanel(mod_widgets.StackPanel):
    def __init__(self,width,gui):
        mod_widgets.StackPanel.__init__(self,width)
        self.headingWidget = mod_widgets.Image(gui.graphicsMap['MISC_ABILITIES'])
        self.gui = gui
        self.buttonXPos = width-28
        self.refresh()

    def refresh(self):
        self.widgets = []
        player = self.gui.currentPlayer
        if player:
            self.widgets.append(self.headingWidget)
            for verb in player.abilities:
                command = mod_command.Command(verb,player)
                widgetCoordMap = {}
                textSurface = self.gui.distanceMapFont.render(verb.name, 1, (0, 0, 0))
                text = mod_widgets.Image(textSurface)
                widgetCoordMap[text] = (10,10)
                button = CommandButton(command,self.gui)
                widgetCoordMap[button] = (self.buttonXPos,4)
                self.widgets.append(mod_widgets.CoordPanel((256,32),widgetCoordMap))
        

class InventoryPanel(mod_widgets.StackPanel):
    def __init__(self,width,gui):
        mod_widgets.StackPanel.__init__(self,width)
        self.headingWidget = mod_widgets.Image(gui.graphicsMap['MISC_INVENTORY'])
        self.gui = gui
        self.buttonXPos = width-28
        self.refresh()
        # 256x400 for now
        
    def refresh(self):
        self.widgets = []
        player = self.gui.currentPlayer
        if player:
            self.widgets.append(self.headingWidget)
            for itemIndex,item in enumerate(player.items):
                widgetCoordMap = {}
                icon = mod_widgets.Image(self.gui.graphicsMap[item.glyph])
                textSurface = self.gui.distanceMapFont.render(item.glyph, 1, (0, 0, 0))
                text = mod_widgets.Image(textSurface)
                widgetCoordMap[icon] = (0,0)
                widgetCoordMap[text] = (36,10)
                
                commands = reversed(mod_command.getCommandsForItem(player,item))
                xPos = self.buttonXPos
                for command in commands:
                    if command.isPossible():
                        button = CommandButton(command,self.gui)
                        widgetCoordMap[button] = (xPos,4)
                        xPos -= 28
                self.widgets.append(mod_widgets.CoordPanel((256,32),widgetCoordMap))


class SpaceInfoPanel(mod_widgets.StackPanel):
    def __init__(self,width,gui):
        mod_widgets.StackPanel.__init__(self,width)
        self.headingWidget = mod_widgets.Image(gui.graphicsMap['MISC_STUFFHERE'])
        self.gui = gui
        self.buttonXPos = width-28
        self.refresh()

    def refresh(self):
        self.widgets = []
        player = self.gui.currentPlayer
        levelMemory = self.gui.currentLevelMemory
        
        if player and player.location:
            coords = player.location[1]
            items = levelMemory.itemMap.get(coords)
            if items:
                self.widgets.append(self.headingWidget)
                for itemIndex,itemGhost in enumerate(items):
                    widgetCoordMap = {}
                    icon = mod_widgets.Image(self.gui.graphicsMap[itemGhost.glyph])
                    textSurface = self.gui.distanceMapFont.render(itemGhost.glyph, 1, (0, 0, 0))
                    text = mod_widgets.Image(textSurface)
                    widgetCoordMap[icon] = (0,0)
                    widgetCoordMap[text] = (36,10)
                    
                    commands = reversed(mod_command.getCommandsForItem(player,itemGhost))
                    xPos = self.buttonXPos
                    for command in commands:
                        if command.isPossible():
                            button = CommandButton(command,self.gui)
                            widgetCoordMap[button] = (xPos,4)
                            xPos -= 28
                    self.widgets.append(mod_widgets.CoordPanel((256,32),widgetCoordMap))


class GUI:
    def __init__(self,game):
        size = (1200,825)
        self.screen = pygame.display.set_mode(size)
        self.graphicsMap = {}
        self.loadGraphics()
        pygame.font.init()
        self.distanceMapFont = pygame.font.Font(None, 16)
        
        self.currentPlayer = game.player
        self.currentLevel = game.player.location[0]
        self.currentLevelMemory = game.player.brain.memory.getLevelMemory(self.currentLevel.number)
        
        paneMap = {}
        
        self.gamePanel = GamePanel(game,self)
        self.gamePanelScroller = mod_widgets.ScrollPane((944,665),self.gamePanel,20)
        
        paneMap[self.gamePanelScroller] = (0,32)
        self.statusBar = StatusBar((944,32),self)
        paneMap[self.statusBar] = (0,0)
        self.messageBox = MessageBox((944,128),self)
        paneMap[self.messageBox] = (0,697)
        
        self.spaceInfoPanel = SpaceInfoPanel(256,self)
        self.inventoryPanel = InventoryPanel(256,self)
        self.abilitiesPanel = AbilitiesPanel(256,self)
        self.sidePanel = mod_widgets.StackPanel(256)
        self.sidePanel.widgets.append(self.spaceInfoPanel)
        self.sidePanel.widgets.append(self.inventoryPanel)
        self.sidePanel.widgets.append(self.abilitiesPanel)
        paneMap[self.sidePanel] = (944,0)
        
        endTurnButton = CommandButton(staticEndTurnCommand,self)
        paneMap[endTurnButton] = (944,793)
        
        self.masterPanel = mod_widgets.CoordPanel(size,paneMap)
        
        self.clock = pygame.time.Clock()
        
        self.screen.fill((0,0,128))
        self.game = game
        
        self.command = None
        
        self.possibleCommand = None
        
        self.messages = []
        
        self.gamePanel.displayNewLevel(self.currentLevel)
        
        
    def loadGraphics(self):
        with open('gfx/gfxmapping.dat') as file:
            firstLine = True
            for line in file:
                line = line.strip()
                if firstLine:
                    colorKey = map(int,tuple(line.split(',')))
                    firstLine = False
                else:
                    properties = line.split(',')
                    filename = 'gfx/'+properties[1]
                    image = pygame.image.load(filename).convert()
                    image.set_colorkey(colorKey)
                    if len(properties) > 2:
                        image.set_alpha(int(properties[2]))
                    self.graphicsMap[properties[0]] = image
    
    
    def takeTurn(self,playerBrain):
        actor = playerBrain.actor
        self.currentPlayer = actor
        #print playerBrain.visibleTiles
        self.currentLevel = actor.location[0]
        self.currentLevelMemory = playerBrain.memory.getLevelMemory(self.currentLevel.number)
        
        scrollPoint = self.gamePanel.getCoordsInPanel(actor.location[1])
        #self.gamePanelScroller.scrollToPoint(scrollPoint)
        self.scrollIfNecessary(scrollPoint)
        
        finished = False
        while not finished:
            level = actor.location[0]
            if level != self.currentLevel:
                self.gamePanel.displayNewLevel(level)
                self.currentLevel = level
                self.currentLevelMemory = mod_player.staticPlayerBrain.getLevelMemory(level.number)
            self.inventoryPanel.refresh()
            self.spaceInfoPanel.refresh()
            self.abilitiesPanel.refresh()
            self.go('go')
            if self.command == staticEndTurnCommand:
                finished = True
            elif self.command.AP and actor.AP < self.command.AP:
                self.messages.append('Not enough AP!')
            else:
                self.command.doIt()
                
            self.command = None
            self.possibleCommand = None
            
            playerBrain.generateDistanceMap(structuralOnly=False,visibleTilesOnly=True)


    def go(self,mode):
        actor = self.currentPlayer
        level = actor.location[0]
        #level = actor.location 
        
        if isinstance(mode,Animation):
            centerPoint = mode.getCenterPoint()
            if centerPoint:
                self.scrollIfNecessary(mode.getCenterPoint())
        
        finished = False
        while not finished:
            
            self.mode = mode
            # This may be unnecessary:
            self.clock.tick(25) # maximum number of frames per second
            
            events = pygame.event.get()
            
            # Now the main event-processing loop
            if events:
                for event in events:
                    if mode == 'go' or mode == 'target':
                        if event.type == pygame.QUIT:
                            self.quit()
                        elif event.type == pygame.KEYDOWN:
                            if event.key == pygame.K_ESCAPE:
                                if mode == 'target':
                                    self.command = None
                                    mode = 'go'
                                    self.mode = mode
                                else:
                                    self.quit()
                            elif event.key == pygame.K_RETURN:
                                self.command = staticEndTurnCommand
                                
                            # Scrolling:
                            elif event.key == pygame.K_DOWN:
                                self.gamePanelScroller.scroll((0,1))
                            elif event.key == pygame.K_UP:
                                self.gamePanelScroller.scroll((0,-1))
                            elif event.key == pygame.K_LEFT:
                                self.gamePanelScroller.scroll((-1,0))
                            elif event.key == pygame.K_RIGHT:
                                self.gamePanelScroller.scroll((1,0))
                                
                        elif event.type == pygame.MOUSEMOTION:
                            self.possibleCommand = None
                            self.masterPanel.handleMouseOver(event.pos)
                        elif event.type == pygame.MOUSEBUTTONDOWN:
                            self.masterPanel.handleClick(event.pos,event.button)
                            
            self.drawMasterPanel()
            if isinstance(mode,Animation) and mode.finished:
                finished = True
            elif mode == 'go' and self.command:
                if self.command.targetType == None:
                    finished = True
                else:
                    mode = 'target'
            if mode == 'target' and self.command.target:
                finished = True
    
    def drawMasterPanel(self):
        self.screen.blit(self.masterPanel.update(),(0,0))
        pygame.display.update()
        
    def playMoveAnimation(self,moveEvent):
        self.go(MoveAnimation(moveEvent,self))
    
    def playProjectileAnimation(self,projectileEvent):
        self.go(ProjectileAnimation(projectileEvent,self))
    
    def playAOEAnimation(self,areaOfEffectEvent):
        self.go(AOEAnimation(areaOfEffectEvent,self))
    
    def scrollIfNecessary(self,point):
        if not self.gamePanelScroller.isPointVisible(point):
            self.gamePanelScroller.scrollToPoint(point)
    
    def quit(self):
#        f = open('savegame.dat','w')
#        self.game.save(f)
#        f.close()
        sys.exit()

theGUI = None